package com.ray.validate.support.rule;

import com.ray.validate.support.utils.PropertyUtils;
import com.ray.validate.support.utils.ValidateUtil;

import javax.validation.constraints.Future;
import javax.validation.constraints.Past;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.chrono.ChronoZonedDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * @author bo shen
 * @Description: Past校验
 * @Class: FutureRule
 * @Package com.ray.validate.support.rule
 * @date 2020/3/18 9:52
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
public class PastRule implements Rule<Past> {

    @Override
    public void rule(Object bean, String fieleName, Past annotation) {
        Object value = PropertyUtils.getObjectProperty(bean, fieleName);
        Long now = System.currentTimeMillis();
        if (value != null) {
            if (value instanceof Date) {
                ValidateUtil.isTrue(((Date) value).getTime() > now, annotation.message());
            } else if (value instanceof Calendar) {
                ValidateUtil.isTrue(((Calendar) value).getTimeInMillis() > now, annotation.message());
            } else if (value instanceof OffsetDateTime) {
                ValidateUtil.isTrue(((OffsetDateTime) value).toInstant().toEpochMilli() > now, annotation.message());
            } else if (value instanceof Instant) {
                ValidateUtil.isTrue(((Instant) value).toEpochMilli() > now, annotation.message());
            }else if (value instanceof ChronoZonedDateTime) {
                ValidateUtil.isTrue(((ChronoZonedDateTime) value).toInstant().toEpochMilli() > now, annotation.message());
            }
        }
    }

    @Override
    public void rule(Object value, Past annotation) {
        Long now = System.currentTimeMillis();
        if (value != null) {
            if (value instanceof Date) {
                ValidateUtil.isTrue(((Date) value).getTime() > now, annotation.message());
            } else if (value instanceof Calendar) {
                ValidateUtil.isTrue(((Calendar) value).getTimeInMillis() > now, annotation.message());
            } else if (value instanceof OffsetDateTime) {
                ValidateUtil.isTrue(((OffsetDateTime) value).toInstant().toEpochMilli() > now, annotation.message());
            } else if (value instanceof Instant) {
                ValidateUtil.isTrue(((Instant) value).toEpochMilli() > now, annotation.message());
            }else if (value instanceof ChronoZonedDateTime) {
                ValidateUtil.isTrue(((ChronoZonedDateTime) value).toInstant().toEpochMilli() > now, annotation.message());
            }
        }
    }
}
